<template>
	<view class="content">
		<u-sticky>
			<view
				style="width:750rpx;height: 150rpx;background:linear-gradient(to bottom, #273965, #353f56);margin-bottom: 10rpx;">
				<view class="types">
					<u-tabs :list="types" :current="activeTab" @click="selectType" :activeStyle="{
						color: 'white',
						fontWeight: 'bold',
						fontSize:'l0px',
						transform: 'scale(1.05)',
					 }" :inactiveStyle="{
						color: 'white',
						transform: 'scale(1)',
					 }"></u-tabs>
				</view>
				<view class="types_son">
					<u-tabs :current="activeTabs" @change="onTabChange" :activeStyle="{
						color: 'white',
						fontWeight: 'bold',
					 }" :inactiveStyle="{
						color: 'white',
						transform: 'scale(1)',
					 }" :list="typeson" @click="selectImg" lineWidth="30"></u-tabs>
				</view>
			</view>
		</u-sticky>
		<u-loading-page :loading="loading" bg-color="#e8e8e8" loading-text="loading..."></u-loading-page>
		<view class="host">
			<view class="host_body" v-for="(item,index) in hostList" :key="index">
				<view class="imageing" v-if="item.imgPath.split(',')[0]" @click="previewImage(index)">
					<img style="width: 345rpx;" mode="widthFix" :src="baseUrl+item.imgPath.split(',')[0]">
				</view>
				<view class="host_darkness">
					<u-row class="ty" justify="space-between">
						<u-col span="6" class="yui">
							<p class="yui">{{item.name}}</p>
						</u-col>
						<u-col span="6">
							<u-row justify="start">
								<u-col span="2">
								</u-col>
								<u-col span="4">
									<view class="animated like" hover-class="heartBeat">
										<image class="like" @click="toggleLike(index)"
											:src="item.isLiked ? '../../static/icon/点赞.png' : '../../static/icon/未点赞.png'"
											style="width: 40rpx; height: 40rpx;"></image>
									</view>
								</u-col>
								<u-col span="4">
									<view class="animated like" hover-class="heartBeat">
										<image class="like" @click="toggleCollection(index)"
											:src="item.isCollection ? '../../static/icon/收藏2.png' : '../../static/icon/收藏.png'"
											style="width: 40rpx; height: 40rpx;"></image>
									</view>
								</u-col>
							</u-row>
						</u-col>
					</u-row>
				</view>
			</view>
		</view>
	<!-- 	<tab-bar :current="0"></tab-bar> -->
		<u-toast ref="uToast" />
		<!-- 弹出框 -->
		<view>
			<u-popup :show="show" mode="bottom" @close="close">
				<view class="LoginAlert">
					<p class="AlertText">你未登录，请先登录</p>
					<view class="AlertButton">
						<u-button type="success" text="登录" @click="getEquipment()"></u-button>
					</view>
				</view>
			</u-popup>
		</view>
	</view>
</template>
<script>
	import request from '@/util/request'
	export default {
		created() {
			//#ifdef MP-WEIXIN
			wx.showShareMenu({
				withShareTicket: true,
				menus: ['shareAppMessage', 'shareTimeline']
			});
			//#endif
		},
		onShareAppMessage(res) { //发送给朋友
			return {
				title: this.title,
				imageUrl: this.thumb,
			}
		},
		onShareTimeline(res) { //分享到朋友圈
			return {
				title: this.title,
				imageUrl: this.thumb,
			}
		},
		onLoad(query) {
			this.handleQuery(query)
			this.login()
			this.IsLogin();
		},
		onShow() {
			this.handleDeviceInfo()
		},
		data() {
			return {
				title:'Absolut Uniq 银饰·玻璃·皮具·团建',
				thumb:'../../static/icon/title.jpg',
				show: false,
				deviceId: 0,
				loadFlag: true,
				imgTypeId: 0,
				activeTab: 0,
				activeTabs: 0,
				baseUrl: 'https://absolutuniq.com:8088',
				parent_id: 0,
				parentId: null,
				types: [],
				typeson: [],
				typeId: 0,
				loading: false,
				isLiked: false, // 是否已点赞
				isCollection: false, //是否已收藏
				status: 'loadmore',
				hostList: [],
				isLogin: false,
				pageNum: 0,
				pageSize: 8,
				hostListAll: [],
			}
		},
		onReachBottom() {
			// if (this.pageNum * this.pageSize >= this.hostListAll.length) {
			// 	return; // 防止重复加载或者数据加载完毕
			// }
			if(this.hostList.length == this.hostListAll.length)
			this.loading = true
			this.pageNum++;
			const pageData= this.getPageData()
			this.hostList.push(...pageData)
			setTimeout(() => {
				// 这里放置你想要在等待5秒后执行的代码
				this.loading = false
			}, 1000);
			//数据触底以后，加载新的数据（就是加载新一页的数据）
		},
		computed: {
			divStyle() {
				return {
					color: 'green',
					border: '1px solid red'
				};
			},
		},
		methods: {
			 getPageData() { //分页
			      const start = this.pageNum * this.pageSize;
			      const end = start + this.pageSize;
				  return this.hostListAll.slice(start, end);
			},
			//判断是否登录
			IsLogin() {
				const isLogin = uni.getStorageSync('isLogin');
				this.isLogin = isLogin;
				
			},
			login() {
				wx.login({
					success: res => {
						const code = res.code; //
					}
				})
			},
			//登录
			getEquipment() {
				wx.getUserProfile({
					desc: '获取你的头像和昵称',
					success: (res) => {
						
						request({
							url: '/users/login',
							method: 'POST',
							data: this.deviceId
						}).then(res => {
							
						}).catch(err => {
							
						});
						uni.setStorage({
							key: 'isLogin',
							data: true
						})
						uni.setStorage({
							key: 'isUser',
							data: res.userInfo
						})
						uni.reLaunch({
							url: "/pages/home/index"
						})
					},
					fail: (err) => {
						
					}
				});
			},
			//取消弹出框
			close() {
				this.show = false
				
			},
			handleQuery(query) { //返回上次的路径
				if (query.id) {
					this.imgTypeId = parseInt(query.id)
					uni.setStorageSync("typeId", this.imgTypeId)
					this.loading = true
					this.getParentIdByChildId();
				} else {
					this.loading = true
					this.getType();
				}
				this.loadFlag = false
			},
			handleDeviceInfo() { //实时更新点赞收藏
				// 获取设备信息
				const systemInfo = uni.getSystemInfoSync();
				let deviceId = systemInfo.deviceId;
				this.deviceId = parseInt(deviceId);
				
				if (this.loadFlag) {
					let typeId = uni.getStorageSync("typeId")
					let parent_id = uni.getStorageSync("parent_id")
					this.selectImgByTypeIds(typeId);
				} else {
					this.loadFlag = true
				}
			},
			onTabChange(index) {
				this.activeTabs = index.index; // 更新选中的索引
			},
			showToast() {
				this.$refs.uToast.show({
					title: '加载数据',
					message: "加载数据",
					type: 'success',
				})
			},
			//查询
			getParentIdByChildId() {
				request({
					url: '/imgtype/imgtype/getParentIdByChildId?id=' + this.imgTypeId,
				}).then(res => {
					let parentId = res.data.data['parentId'];
					this.getTypes(parentId);
				}).catch(err => {
					
				});
			},
			getTypes(parentId) { //查询一级树
				request({
					url: '/imgtype/imgtype/parentIdList?id=0',
					method: 'get'
				}).then(res => {
					// 查找 this.parentId 在 res.data 中的索引
					const index = res.data.findIndex(item => item.id === parentId);
					// 设置全局变量
					this.activeTab = index
					this.types = res.data
					if (res.data.length > 0) {
						this.parent_id = parentId;
						this.getTypeSons();
					}
				})
				this.loading = false
			},
			getTypeSons() { //查询二级树
			
				request({
					url: '/imgtype/imgtype/parentIdList?id=' + this.parent_id,
					method: 'get'
				}).then(res => {
					// 查找 imgTypeId 在 res.data 中的索引
					const index = res.data.findIndex(item => item.id === this.imgTypeId);
					this.activeTabs = index
					this.typeson = res.data
					if (res.data.length > 0) {
						this.typeId = this.imgTypeId;
						this.selectImgByTypeId()
					}
				})
			},
			//点赞方法
			toggleLike(index) {
				const isLogin = this.isLogin;
				if (isLogin) {
					// 切换点赞状态
					this.hostList[index].isLiked = !this.hostList[index].isLiked;
					// 准备发送到后端的数据
					const imgId = this.hostList[index].id; // 假设每个图像对象有一个 id
					const isLiked = this.hostList[index].isLiked;
					// 发送请求到后端
					request({
						url: '/favorites/favorites/toggleLike', // 假设这是处理点赞的后端 API 路径
						method: 'POST',
						data: {
							userId: this.deviceId, // 用户 ID
							imgManageId: imgId, // 图像 ID
							liked: isLiked // 当前的点赞状态
						}
					}).then(res => {
						
					}).catch(err => {
					
					});
				} else {
					this.show = true
				}
			},
			// 收藏方法
			toggleCollection(index) {
				const isLogin = this.isLogin;
				if (isLogin) {
					//切换收藏状态
					this.hostList[index].isCollection = !this.hostList[index].isCollection;
					// 准备发送到后端的数据
					const imgId = this.hostList[index].id; // 假设每个图像对象有一个 id
					const isCollection = this.hostList[index].isCollection;
					// 发送请求到后端
					request({
						url: '/favorites/favorites/toggleCollection', // 假设这是处理点赞的后端 API 路径
						method: 'POST',
						data: {
							userId: this.deviceId, // 用户 ID
							imgManageId: imgId, // 图像 ID
							col: isCollection // 当前的收藏状态
						}
					}).then(res => {
				
					}).catch(err => {
						
					});
				} else {
					this.show = true
				}
			},
			getType() { //查询一级树
				request({
					url: '/imgtype/imgtype/parentIdList?id=0',
					method: 'get'
				}).then(res => {
					this.types = res.data
					this.types = res.data.slice(0, res.data.length - 1);//不要最后一条的团建活动
					if (res.data.length > 0) {
						this.parent_id = res.data[0].id;
						this.getTypeSon();
					}
				})
				this.loading = false
			},
			getTypeSon() { //查询二级树
				this.pageNum = 0
				this.hostList = []
				request({
					url: '/imgtype/imgtype/parentIdList?id=' + this.parent_id,
					method: 'get'
				}).then(res => {
					this.typeson = res.data
					uni.setStorageSync("typeId", res.data[0].id);
					if (res.data.length > 0) {
						this.typeId = res.data[0].id;
						this.selectImgByTypeId()
					}
				})
			},
			selectType(item) {
				this.activeTabs = 0
				this.parent_id = item.id
				this.getTypeSon();
			},
			selectImgByTypeId() {
				this.pageNum = 0
				this.hostList = []
				this.loading = true; // 开始加载状态
				// 获取图片
				const getImagesRequest = request({
					url: '/imgmanage/imgmanage/selectImgByTypeId?id=' + this.typeId,
					method: 'get'
				});
				// 获取用户点赞图片
				const getLikesRequest = request({
					url: '/favorites/favorites/getUserImageLike?id=' + this.deviceId,
					method: 'get'
				});
				// 获取用户收藏图片
				const getCollectionsRequest = request({
					url: '/favorites/favorites/getUserImageCollection?id=' + this.deviceId,
					method: 'get'
				});
				Promise.all([getImagesRequest, getLikesRequest, getCollectionsRequest]).then(responses => {
					const [imageResponse, likeResponse, collectionResponse] = responses;
					// 处理图片数据
					this.hostList = imageResponse.data.map(item => ({
						...item,
						isCollection: false, // 初始状态为未收藏
						isLiked: false, // 初始状态为未点赞
					}));
					
					if (this.isLogin) {
						// 处理点赞数据
						const likedIds = new Set(likeResponse.data);
						this.hostList = this.hostList.map(item => ({
							...item,
							isLiked: likedIds.has(item.id) // 更新点赞状态
						}));
						// 处理收藏数据
						const collectedIds = new Set(collectionResponse.data);
						this.hostList = this.hostList.map(item => ({
							...item,
							isCollection: collectedIds.has(item.id) // 更新收藏状态
						}));
						
					}
					this.hostListAll = this.hostList;
					this.hostList = this.hostListAll.slice(0,this.pageSize)
					this.loading = false; // 加载结束
				}).catch(error => {
				
					this.loading = false; // 加载结束
				});
			},
			selectImgByTypeIds(typeId) {
				this.pageNum = 0
				this.hostList = []
				this.loading = true; // 开始加载状态
				// 获取图片
				const getImagesRequest = request({
					url: '/imgmanage/imgmanage/selectImgByTypeId?id=' + typeId,
					method: 'get'
				});
				// 获取用户点赞图片
				const getLikesRequest = request({
					url: '/favorites/favorites/getUserImageLike?id=' + this.deviceId,
					method: 'get'
				});
				// 获取用户收藏图片
				const getCollectionsRequest = request({
					url: '/favorites/favorites/getUserImageCollection?id=' + this.deviceId,
					method: 'get'
				});
				Promise.all([getImagesRequest, getLikesRequest, getCollectionsRequest]).then(responses => {
					const [imageResponse, likeResponse, collectionResponse] = responses;
					// 处理图片数据
					this.hostList = imageResponse.data.map(item => ({
						...item,
						isCollection: false, // 初始状态为未收藏
						isLiked: false, // 初始状态为未点赞
					}));
					// 处理点赞数据
					const likedIds = new Set(likeResponse.data);
					this.hostList = this.hostList.map(item => ({
						...item,
						isLiked: likedIds.has(item.id) // 更新点赞状态
					}));
					// 处理收藏数据
					const collectedIds = new Set(collectionResponse.data);
					this.hostList = this.hostList.map(item => ({
						...item,
						isCollection: collectedIds.has(item.id) // 更新收藏状态
					}));
					this.loading = false; // 加载结束
				}).catch(error => {
					
					this.loading = false; // 加载结束
				});
			},
			selectImg(item) {
				if (item) { // 检查 item 是否有效
					this.typeId = item.id;
					this.selectImgByTypeId();
					uni.setStorageSync("typeId", this.typeId);
				} 
			},
			previewImage(index) {
				const imgUrls = this.hostList[index].imgPath.split(",");
				if (imgUrls.length > 0) {
					const newurls = imgUrls.map(item => {
						return item = this.baseUrl + item;
					});
					// 调用预览图片API
					uni.previewImage({
						current: 0, // 当前显示图片索引
						urls: newurls, // 需要预览的图片URL列表
					});
				}
			}
		}
	}
</script>
<style lang="scss">
	.like {
		color: #ffe833;
		filter: none;
		will-change: font-size;
		-webkit-animation: heart 1s cubic-bezier(0.17，8.89，8.32，1.49);
		animation: heart 1s cubic-bezier(0.17，0.89，8.32，1.49);
		width: 40rpx;
		height: 40rpx;
	}

	.noLike {
		width: 40rpx;
		height: 40rpx;
	}

	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.host {
		margin-top: 40rpx;
		margin: 0 auto;
		padding: 0 20rpx;
		column-count: 2;
		column-gap: 20rpx;
	}

	.host_body {
		width: 345rpx;
		border-radius: 20rpx;
		box-sizing: border-box;
		overflow: hidden;
		background-color: #fff;
		break-inside: avoid;
		/*避免在元素内部插入分页符*/
		box-sizing: border-box;
		/* 	margin-top: rpx; */
		margin-bottom: 20rpx;
		box-shadow: 0px 0px 28rpx 1rpx rgba(78, 101, 153, 0.14);
	}

	.imageing {
		width: auto;
		height: auto;
		position: relative;
		/* 使子元素可以相对于这个元素定位 */
	}

	.like-count img {
		margin-right: 5px;
		/* 图标与文本之间的间距 */
		width: 15px;
		/* 只设置宽度，高度自动调整 */
		height: 15px;
	}

	.types {
		width: 95%;
		margin: 0 auto;
		height: 70rpx;
	}

	.types_son {
		width: 80%;
		margin: 0 auto;
		height: 70rpx;
	}

	.imageing_img {
		width: 345rpx;
		height: auto;
	}

	.host_darkness {
		padding-left: 16rpx;
		font-size: 25rpx;
		margin-top: 15rpx;
		padding-bottom: 22rpx;
	}

	.darkness_silence {
		font-weight: 800;
		margin-top: 12rpx;
		font-size: 27rpx;
		margin-left: 10rpx;
	}

	.yui {
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		margin-top: 5px;
	}

	/* 弹出框 */
	.LoginAlert {
		width: 95%;
		height: 200rpx;
		text-align: center;
		font-size: 30rpx;
	}

	/* 弹出框按钮 */
	.AlertButton {
		width: 80%;
		margin: auto;
	}

	/* 弹出框文字 */
	.AlertText {
		margin-top: 20rpx;
		margin-bottom: 20rpx;
	}
</style>